import datetime
import json

from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View

from celery_tasks.orders.tasks import generate_order
from focus_on_rent.settings.dev import QINIU_URL
from focus_on_rent.utils.views import LoginRequiredMixin
from homes.models import House
from orders.models import Order


class OrderAddView(LoginRequiredMixin, View):

    # 提交订单业务
    def post(self, request):
        # 乐观锁在此处不适用，故改为celery
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        # 2.整体检验，个体检验
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': 4103,
                                 'errmsg': '缺少必传参数'})
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '缺少必传参数'})
        # 将时间str转化为date类型
        try:
            start_date = datetime.date(*map(int, start_date.split('-')))
            end_date = datetime.date(*map(int, end_date.split('-')))
        except Exception as e:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '日期格式错误'})
        # 3.判断该时段内是否有用户已经预定
        time_range = (start_date, end_date)
        days = end_date - start_date
        days = int(str(days)[0])
        if days == 0:
            days = 1
        if days <= 0:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '入住时间过短'})
        if house.max_days != 0:
            if days > house.max_days:
                return JsonResponse({'errno': 4004,
                                     'errmsg': '超过最大入住天数'})
        try:
            orders = Order.objects.filter(Q(begin_date__range=time_range) & Q(end_date__range=time_range))
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '数据库查询错误'})
        if orders:
            test = '有数据'
            generate_order.delay(test)

        # 4.生成订单
        user = request.user
        # order_id = timezone.localtime().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        # 5.判断是否已被预定并保存数据
        try:
            order = Order.objects.create(user=user,
                                         house=house,
                                         begin_date=start_date,
                                         end_date=end_date,
                                         days=days,
                                         house_price=house.price,
                                         amount=house.price * days + house.deposit,
                                         status=Order.ORDER_STATUS["WAIT_ACCEPT"],
                                         )
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '创建订单失败'})
        # 6.在房屋数据表中增加订单数
        try:
            house.order_count += 1
            house.save()
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '增加房屋订单数量失败'})

        # 7.返回json数据
        return JsonResponse({"data": {"order_id": order.id},
                             "errno": "0",
                             "errmsg": "下单成功"})


    # 获取订单业务
    def get(self, request):
        # 1.接收参数
        # json_dict = json.loads(request.body.decode())
        role = request.GET.get('role')
        user = request.user
        # 2.判断客户类型
        orders_list = []
        if role == 'custom':
            #     2.1 用户
            #         2.1.1 通过用户id获取订单
            try:
                orders = Order.objects.filter(user=user)
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                     'errmsg': '数据库查询错误'})

        elif role == 'landlord':
            #     2.2 房东
            #         2.2.1 通过用户id获取房屋
            #         2.2.2 通过房屋获取订单
            try:
                houses = House.objects.filter(user=user)
                orders = Order.objects.filter(house__in=houses)
            except Exception as e:
                return JsonResponse({'errno': 4001,
                                     'errmsg': '数据库查询错误'})

        else:
            return JsonResponse({'errno': 4103,
                                 'errmsg': '传递参数有误'})

        for order in orders:
            url = QINIU_URL + order.house.index_image_url
            if order.status == Order.ORDER_STATUS["WAIT_COMMENT"]:
                if role == 'landlord':
                    status = 'ACCEPT'
            status = Order.ORDER_STATUS_ENUM[order.status]
            orders_list.append({
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": status,
                "title": order.house.title})
        # 3. 返回参数
        return JsonResponse({"data": {"orders": orders_list},
                             "errmsg": "OK",
                             "errno": "0"})


class OrderOperationView(LoginRequiredMixin, View):
    # 房东接受或拒绝订单
    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')
        if action == 'reject':
            status = Order.ORDER_STATUS["REJECTED"]
        else:
            status = Order.ORDER_STATUS["WAIT_COMMENT"]
        user = request.user

        try:
            Order.objects.filter(id=order_id).update(status=status,
                                                     comment=reason)
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '数据库查询错误'})

        return JsonResponse({"errno": "0",
                             "errmsg": "操作成功"})

class OrderCommentView(LoginRequiredMixin, View):
    # 评论订单
    def put(self, request, order_id):
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        try:
            Order.objects.filter(id=order_id).update(
                comment=comment,
                status=Order.ORDER_STATUS["COMPLETE"]
            )
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '数据库修改错误'})

        return JsonResponse({"errno": "0",
                             "errmsg": "评论成功"})
